package licode.unisop.auth.adapter.web;

import licode.unisop.auth.exception.AuthErrorCode;
import licode.unisop.client.api.auth.SopUserAuthQuery;
import licode.unisop.client.info.SopTokenInfo;
import licode.unisop.client.inter.HasAuthority;
import licode.unisop.client.utils.SopRequestParse;
import licode.unisop.client.utils.StringUtil;
import licode.unisop.client.vo.SopCredential;
import licode.unisop.log.client.api.CallingLogApi;
import licode.unisop.log.client.api.LoginLogApi;
import licode.unisop.log.client.dto.CallingLogDTO;
import licode.unisop.log.client.dto.LoginLogDTO;
import licode.unisop.log.client.req.CallingLogIn;
import licode.unisop.log.client.req.LoginLogIn;
import licode.unisop.types.AuthConst;
import licode.unisop.unilite.dp.PageData;
import licode.unisop.unilite.result.UniResult;
import licode.unisop.unilite.result.UniReturnResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 定义统一认证平台中心认证相关接口
 *
 * @author licode
 */
@Slf4j
@UniReturnResult
@RestController
@RequestMapping("/uni-auth/v1/token/log/query")
public class AuthorLogQueryController {
    @Resource
    private HttpServletRequest request;

    @Resource
    private LoginLogApi loginLogApi;

    @Resource
    private CallingLogApi callingLogApi;

    @Resource
    private SopUserAuthQuery queryAuth;

    @RequestMapping(value = "/login/page", method = RequestMethod.POST)
    public UniResult<PageData<LoginLogDTO>> queryLoginLogPage(@RequestBody LoginLogIn req) {
        SopTokenInfo tokenInfo = SopRequestParse.getAccessTokenInfo(request);
        SopCredential credential = queryAuth.getCredential(tokenInfo);
        if (null == credential) {
            throw AuthErrorCode.ACCESS_TOKEN_EXPIRED.buildThrow();
        }
        String roleCodes = credential.getBrief().getRoleCodes();
        if (StringUtil.isBlank(roleCodes)) {
            roleCodes = "";
        }

        if (!roleCodes.contains(AuthConst.SYSTEM_ADMIN)) {
            req.setUserId(credential.getBrief().getUserId());
        }

        return UniResult.of(loginLogApi.query(req));
    }

    @RequestMapping(value = "/call/page", method = RequestMethod.POST)
    @HasAuthority(roles=AuthConst.SYSTEM_ADMIN, permits = "system:log:call")
    public UniResult<PageData<CallingLogDTO>> queryCallLogPage(@RequestBody CallingLogIn req) {
        return UniResult.of(callingLogApi.query(req));
    }
}
